// 加载express模块
const express = require('express');
const router = express.Router();
const pool = require('../mysql/pool');

router.use(express.urlencoded());
router.use(express.json());


router.get('/', (req, res, next) => {
    pool.query('select * from dec_list', (err, r) => {
        if (err) {
            next();
        }
        console.log(r);
        res.send({status:'200', message:'ok', data:r});
    })

});


// 删除业务
router.post('/del', (req, res, next) => {
    const { id } = req.body;

    pool.query('delete from dec_list where id = ?', [id], (err, r) => {
        if (err) {
            res.send(Response.error(500, err.message));
            throw err;
        }
        console.log(r);
        res.send({
            status: '200',
            message: 'ok',
        })
    })
});

// 添加数据业务
router.post('/add', (req, res) => {
    const {
        title,
        image,
    } = req.body; //post请求在req.body中


    pool.query('insert into dec_list(id, title, image) values(?, ?, ?)', [null, title, image], (err, r) => {
        if (err) {
            console.log(err);
            throw err;
        }
        res.send({
            status: 200,
            message: 'ok'
        })
    })
})

router.post('/update', (req, res, next) => {
    const {
        title,
        image,
        id
    } = req.body;

    pool.query('update dec_list set title=?, image=? where id = ?', [title, image, id], (err, r) => {
        if (err) {
            return next(err);
        }
        res.send({
            status:200,
            message:'ok'
        })
    })
});


module.exports = router;

